package licode.unisop.unilite.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理地址
 *
 * @author WR
 * @since 2016/6/20 10:46
 */
public class UrlManager {
    public static String getHost(String url) {
        if (null == url) {
            return "";
        }
        int pos = url.indexOf("?");
        if (-1 == pos) {
            return "";
        }
        return url.substring(0, pos);
    }

    public static int getPort(String url) {
        String strHost = getHost(url);
        int pos = strHost.indexOf("?");
        if (-1 == pos) {
            return 0;
        }
        return Integer.parseInt(strHost.substring(pos + 1));
    }

    public static Map<String, String> getParams(String url) {
        String[] urls = checkUrl(url);
        if (null == urls || urls.length != 2) {
            return new HashMap<>();
        }
        return getParams(urls[1].split("&"));
    }

    private static String[] checkUrl(String url) {
        if (null == url) {
            return null;
        }
        String[] urls = url.split("\\?");
        if (urls.length != 2) {
            return null;
        }
        return urls;
    }

    private static Map<String, String> getParams(String[] urls) {
        Map<String, String> params = new HashMap<>();
        for (String s : urls) {
            String[] values = s.split("=");
            if (values.length == 2) {
                params.put(values[0].trim(), values[1].trim());
            }
        }
        return params;
    }

    public static String replaceParam(String url, String name, String value) {
        String[] urls = checkUrl(url);
        if (null == urls || urls.length != 2) {
            return url;
        }
        Map<String, String> params;
        params = getParams(urls[1].split("&"));
        params.remove(name);
        if (null != value) {
            params.put(name, value);
        }
        return urls[0] + "?" + makeUrlParams(params);
    }

    private static String makeUrlParams(Map<String, String> params) {
        StringBuilder paramStr = new StringBuilder();
        if (null == params) {
            return paramStr.toString();
        }
        for (Map.Entry<String, String> it : params.entrySet()) {
            paramStr.append(it.getKey()).append("=").append(it.getValue()).append("&");
        }
        return paramStr.substring(0, paramStr.length() - 1);
    }
}
